# -*- coding: utf-8 -*-
# _author_ =
# Email:
"""
协议：仅支持 HTTPS 传输
url格式：https://{hostname}:{port}/artemis/{uri}
# AK\SK摘要认证
调用 API 时，如果API需要安全认证，首先需要获取API的授权，得到AppKey和AppSecret；
其次，拼接签名字符串，将计算后的签名放在请求的 Header 传入，网关会通过对称计算签名来验证请求者的身份。
"""

import os
import base64
import json
import time
import uuid
import hmac  # hex-based message authentication code 哈希消息认证码
import hashlib  # 提供了很多加密的算法
import requests


class HaiKang:
    def __init__(self):
        self.base_url = "https://117.141.2.214:44444"  # 可以正常访问的IP地址
        # 注意增加/artemis
        
        self.appKey = "20497666"
        self.appSecret = "QerqY5cOXHlwaRiAUQWT"
    
    def headers(self, api_get_address_url="/artemis/api/video/v2/cameras/previewURLs"):
        x_ca_nonce = str(uuid.uuid4())
        x_ca_timestamp = str(int(round(time.time()) * 1000))
        # sign_str 的拼接很关键，不然得不到正确的签名
        sign_str = "POST\n*/*\napplication/json" + "\nx-ca-key:" + self.appKey + "\nx-ca-nonce:" + \
                   x_ca_nonce + "\nx-ca-timestamp:" + x_ca_timestamp + "\n" + \
                   api_get_address_url
        
        temp = hmac.new(self.appSecret.encode(), sign_str.encode(), digestmod=hashlib.sha256)
        signature = base64.b64encode(temp.digest()).decode()
        print("[INFO] 获取到的签名值为：", signature)
        
        headers = {
            "Accept": "*/*",
            "Content-Type": "application/json",
            "x-ca-key": self.appKey,  # appKey，即 AK
            "x-ca-signature-headers": "x-ca-key,x-ca-nonce,x-ca-timestamp",
            "x-ca-signature": signature,  # 需要计算得到的签名，此处通过后台得到
            "x-ca-timestamp": x_ca_timestamp,  # 时间戳
            "x-ca-nonce": x_ca_nonce  # UUID，结合时间戳防重复
        }
        return headers
    
    # 获取监控点的在线流样例
    def examples(self,api_get_address_url="/artemis/api/video/v2/cameras/previewURLs"):
        headers=self.headers(api_get_address_url)
        body = {
            "cameraIndexCode": "36e0421391f7****",
            "streamType": 0,
            "protocol": "rtsp",
        }
        url = self.base_url + api_get_address_url
        results = requests.post(url, data=json.dumps(body), headers=headers, verify=False)
        print(results)
        print(results.json())
        # {'code': '0', 'msg': 'success', 'data': {'url': 'rtsp://ip:554/openUrl/Kp0VqXS'}}
    def pics(self):
        api_get_address_url="/artemis/api/video/v1/pictureInfos"
        headers=self.headers(api_get_address_url)
        body = {
            "pageNo": 1,
            "pageSize": 400,
            "startTime": "2020-07-26T15:00:00.000+08:00",
            "endTime": "2021-07-26T15:00:00.000+08:00",
        }
        url = self.base_url + api_get_address_url
        results = requests.post(url, data=json.dumps(body), headers=headers, verify=False)
        print(results)
        print(results.json())
        # {'code': '0', 'msg': 'success', 'data': {'url': 'rtsp://ip:554/openUrl/Kp0VqXS'}}
if __name__ == '__main__':
    c=HaiKang()
    c.pics()
